﻿using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Diagnostics;
using System.Timers;
using MessageBox = System.Windows.MessageBox;
using TimerType = System.Timers.Timer;
using Haidou.Wpf.UI.Windows;
using Wpf.Ui.Controls; // 引用Wpf.Ui

namespace Haidou.Wpf.UI
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
        public ObservableCollection<FeatureItem> Features { get; } = new();
        public ObservableCollection<LinkCategory> LinkCategories { get; } = new();
        private LinkCategory _selectedCategory;
        public LinkCategory SelectedCategory { get => _selectedCategory; set { _selectedCategory = value; } }

        // Search suggestions
        public ObservableCollection<string> SearchSuggestions { get; } = new();
        public bool IsSuggestionOpen { get; set; }
        private int _suggestionIndex = -1;
        private readonly TimerType _suggestTimer;
        private DesktopToolsPanel _desktopPanel;
        private UIElement _mainContentCache;

        public ObservableCollection<BreadcrumbBarItem> BreadcrumbItems { get; } = new();

        public MainWindow()
		{
			InitializeComponent();
			DataContext = this;
            LoadFeatures();
            LinkCategories.Add(new LinkCategory("精选", new()
            {
                new QuickLink("腾讯", "https://www.qq.com"),
                new QuickLink("空间", "https://qzone.qq.com"),
                new QuickLink("百度", "https://www.baidu.com"),
                new QuickLink("贴吧", "https://tieba.baidu.com"),
                new QuickLink("网易", "https://www.163.com"),
                new QuickLink("微博", "https://weibo.com"),
                new QuickLink("知乎", "https://www.zhihu.com"),
                new QuickLink("B站", "https://www.bilibili.com"),
                new QuickLink("抖音", "https://www.douyin.com"),
                new QuickLink("GitHub", "https://github.com"),
                new QuickLink("掘金", "https://juejin.cn"),
                new QuickLink("CSDN", "https://www.csdn.net")
            }));
            if (LinkCategories.Count > 0) SelectedCategory = LinkCategories[0];
            _suggestTimer = new TimerType(300) { AutoReset = false };
            _suggestTimer.Elapsed += SuggestTimer_Elapsed;

            BreadcrumbItems.Add(new BreadcrumbBarItem() { Content = "桌面工具" });
		}

        private void SuggestTimer_Elapsed(object? sender, ElapsedEventArgs e) => Dispatcher.Invoke(LoadSuggestionsInternal);

        private void LoadSuggestionsInternal()
        {
            var text = SearchBox.Text?.Trim();
            SearchSuggestions.Clear();
            if (string.IsNullOrWhiteSpace(text)) { IsSuggestionOpen = false; RefreshBindings(); return; }
            string[] suffix = { "天气", "旅游攻略", "旅游攻略景点必去", "地铁", "大学", "天气预报15天", "天气预报", "有哪些好玩的", "属于哪个省", "历史", "美食" };
            foreach (var s in suffix) SearchSuggestions.Add(text + s);
            IsSuggestionOpen = SearchSuggestions.Count > 0; _suggestionIndex = -1; RefreshBindings();
        }

        private void RefreshBindings() { var dc = DataContext; DataContext = null; DataContext = dc; }

        private void SearchBox_TextChanged(object sender, TextChangedEventArgs e) { _suggestTimer.Stop(); _suggestTimer.Start(); }

        private void SearchBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (!IsSuggestionOpen) return;
            if (e.Key == Key.Down) { _suggestionIndex = (_suggestionIndex + 1) % SearchSuggestions.Count; UpdateTextByIndex(); e.Handled = true; return; }
            if (e.Key == Key.Up) { _suggestionIndex = (_suggestionIndex - 1 + SearchSuggestions.Count) % SearchSuggestions.Count; UpdateTextByIndex(); e.Handled = true; return; }
            if (e.Key == Key.Escape) { IsSuggestionOpen = false; RefreshBindings(); e.Handled = true; return; }
            if (e.Key == Key.Enter) { ExecuteSearch(); e.Handled = true; return; }
        }

        private void UpdateTextByIndex()
        {
            if (_suggestionIndex >= 0 && _suggestionIndex < SearchSuggestions.Count)
            {
                SearchBox.TextChanged -= SearchBox_TextChanged; // prevent re-query while navigating
                SearchBox.Text = SearchSuggestions[_suggestionIndex];
                SearchBox.CaretIndex = SearchBox.Text.Length;
                SearchBox.TextChanged += SearchBox_TextChanged;
            }
        }

        private void Suggestion_Click(object sender, MouseButtonEventArgs e)
        { if (sender is Border b && b.Tag is string s) { SearchBox.Text = s; ExecuteSearch(); } }

        private void ExecuteSearch()
        {
            var text = SearchBox.Text?.Trim(); if (string.IsNullOrWhiteSpace(text)) return; IsSuggestionOpen = false; RefreshBindings(); MessageBox.Show($"搜索: {text}");
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e) => ExecuteSearch();

		private void FeatureCard_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			if (sender is Border b && b.Tag is string key)
			{
				if (key == "DESKTOP")
				{
					ShowDesktopPanel();
				}
				else
				{
					MessageBox.Show($"打开功能: {key}");
				}
			}
		}

        private void ShowDesktopPanel()
        {
            if (_desktopPanel == null)
            {
                _desktopPanel = new DesktopToolsPanel();
                _desktopPanel.BackClicked += DesktopPanel_BackClicked;
            }
            if (_mainContentCache == null)
            {
                _mainContentCache = MainContentPresenter.Content as UIElement;
            }
            MainContentPresenter.Content = _desktopPanel;
            BreadcrumbItems.Clear();
            BreadcrumbItems.Add(new BreadcrumbBarItem() { Content = "桌面工具" });
        }

        private void DesktopPanel_BackClicked(object sender, RoutedEventArgs e)
        {
            if (sender is ShutdownTimerPanel shutdownPanel)
            {
                MainContentPresenter.Content = shutdownPanel;
                BreadcrumbItems.Clear();
                BreadcrumbItems.Add(new BreadcrumbBarItem() { Content = "桌面工具" });
                BreadcrumbItems.Add(new BreadcrumbBarItem() { Content = "定时关机" });
            }
            else if (sender == _desktopPanel)
            {
                if (MainContentPresenter.Content is ShutdownTimerPanel)
                {
                    MainContentPresenter.Content = _desktopPanel;
                    BreadcrumbItems.Clear();
                    BreadcrumbItems.Add(new BreadcrumbBarItem() { Content = "桌面工具" });
                }
                else if (_mainContentCache != null)
                {
                    MainContentPresenter.Content = _mainContentCache;
                    BreadcrumbItems.Clear();
                }
            }
        }

        private void LoadFeatures()
        {
            Features.Add(new FeatureItem("桌面工具", "待办提醒，心率监测，定制桌面等", "DESKTOP", "M2 2 H10 V10 H2 Z M12 2 H20 V10 H12 Z M2 12 H10 V20 H2 Z M12 12 H20 V20 H12 Z"));
            Features.Add(new FeatureItem("会话助手", "AI 对话与上下文问答", "CHAT", "M10 2 L18 10 L10 18 L2 10 Z"));
            Features.Add(new FeatureItem("知识检索", "文档/笔记语义搜索", "SEARCH", "M8 2 L12 2 L12 8 L18 8 L18 12 L12 12 L12 18 L8 18 L8 12 L2 12 L2 8 L8 8 Z"));
            Features.Add(new FeatureItem("文件解析", "批量读取与结构化提取", "PARSE", "M4 2 H16 L20 6 V18 H4 Z"));
            Features.Add(new FeatureItem("自动脚本", "任务流与自动化组合", "SCRIPT", "M4 2 H18 V6 H8 V10 H16 V14 H8 V18 H4 Z"));
            Features.Add(new FeatureItem("模型管理", "本地/远程模型状态", "MODEL", "M10 2 A8 8 0 1 1 9.99 2 Z"));
            Features.Add(new FeatureItem("系统设置", "外观 / 快捷键 / 偏好", "SETTINGS", "M10 2 L12 4 L16 4 L18 10 L16 16 L12 16 L10 18 L8 16 L4 16 L2 10 L4 4 L8 4 Z"));
            Features.Add(new FeatureItem("数据中心", "缓存、索引与统计", "DATA", "M4 4 H18 V8 H4 Z M4 10 H18 V14 H4 Z M4 16 H18 V20 H4 Z"));
            Features.Add(new FeatureItem("插件扩展", "扩展市场与管理", "PLUGIN", "M4 2 H12 V8 H8 V12 H4 Z M12 8 H16 V12 H12 Z M16 8 H20 V16 H16 Z"));
            Features.Add(new FeatureItem("更多...", "即将上线的功能预览", "MORE", "M4 10 A2 2 0 1 1 4 9.99 Z M10 10 A2 2 0 1 1 10 9.99 Z M16 10 A2 2 0 1 1 16 9.99 Z"));
        }

        private void BtnMin_Click(object sender, RoutedEventArgs e) => WindowState = WindowState.Minimized;
        private void BtnMax_Click(object sender, RoutedEventArgs e) { WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; UpdateMaxButtonIcon(); }
        private void BtnClose_Click(object sender, RoutedEventArgs e) => Close();

        private void QuickLink_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (sender is Border b && b.Tag is QuickLink link)
            {
                try { Process.Start(new ProcessStartInfo(link.Url) { UseShellExecute = true }); }
                catch { MessageBox.Show("无法打开链接", "错误"); }
            }
        }

        private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2) { BtnMax_Click(sender, e); return; }
            if (e.ButtonState == MouseButtonState.Pressed) DragMove();
        }

        private void Window_StateChanged(object sender, System.EventArgs e) => UpdateMaxButtonIcon();
        private void UpdateMaxButtonIcon() { if (BtnMax == null) return; BtnMax.Content = WindowState == WindowState.Maximized ? "❐" : "▢"; }
    }

    public record FeatureItem(string Title, string Subtitle, string Key, string Icon);
    public record QuickLink(string Name, string Url) { public string Display => Name.Length > 2 ? Name.Substring(0, 2) : Name; }
    public class LinkCategory { public string Name { get; } public ObservableCollection<QuickLink> Links { get; } public LinkCategory(string name, ObservableCollection<QuickLink> links){ Name=name; Links=links; } }
}